Skip to content

Extension method to conveniently download a file - #136

Open
Jericho wants to merge 11 commits into
Pathoschild:developfrom
Jericho:GH-135_download_file
Open

Jericho wants to merge 11 commits into
Pathoschild:developfrom
Jericho:GH-135_download_file

Conversation

@Jericho

@Jericho Jericho commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

Download a resource, save it locally and report progress as data is being downloaded.

Resolves #135

Jericho and others added 10 commits November 15, 2026 14:04
This fixes a few edge cases:
- downloads finishing without a guaranteed 100% progress update;
- progress reporting invalid percentages (e.g. 250%) if the server provides an incorrect Content-Length;
- progress never reported if the server provides no Content-Length;
- a DivideByZeroException if the server provides a zero Content-Length.
This applies our pre-existing fixes like Pathoschild#126 to the new code.
We reported progress on every chunk read, but that could lead to a large number of callbacks when downloading a large file over a fast connection (e.g. thousands per second). The progress reports are now throttled to one per 250ms at most.
@Pathoschild

Copy link
Copy Markdown
Owner

This looks good overall; thanks for the PR!

There's one edge case I'm not sure how we should handle: when used with [Set|With]Options(ignoreHttpErrors: true), a server error will silently get downloaded as the file content, which probably isn't what the user would expect. The extension could maybe return a metadata object (e.g. { Success: false, Error: "..." }), but that might be a bit awkward.

lastTickReported = tick; // workaround: `Environment.TickCount` eventually wraps around, which would stop any further progress updates

// notify progress tracker
if (contentLength > 0 && tick >= lastTickReported + throttleMilliseconds)

@Jericho Jericho Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than throttling progress to once per arbitrary period of 250 ticks, go back to the previous logic and convert percentDownloaded and lastReportedProgress variables to int. The line if (percentDownloaded > lastReportedProgress) will ensure we report progress at most once per percent for a total maximum of 100 progress reports per download. That would keep the logic simple AND prevent overwhelming.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Something like this:

        // stream file to disk
        int lastReportedProgress = 0;

        int bytesRead;
        long totalBytesRead = 0L;
        byte[] buffer = new byte[bufferSize];

        while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) > 0)
        {
            // stream next chunk
            await fileStream.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
            totalBytesRead += bytesRead;

            // notify progress tracker
            if (contentLength > 0)
            {
                // Math.Min is used to avoid reporting more than 100%
                int percentDownloaded = Math.Min((int)((totalBytesRead / (contentLength * 1d)) * 100), 100);

                // report progress if percentage has increased since the last report (to avoid flooding the progress reporter with updates)
                if (percentDownloaded > lastReportedProgress)
                {
                    progress?.Report(percentDownloaded);
                    lastReportedProgress = percentDownloaded;
                }
            }
        }

        // send final progress update
        if (lastReportedProgress < 100)
            progress?.Report(100);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One more thing: if you accept my suggestion, you can also change the progress reporter to:

IProgress<int>? progress = null

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would be elegant, but it'd cause the opposite problem: downloading a large file over a slow connection could go a long time between progress updates, so a stalled download would be indistinguishable from a slow one. With time throttling, slow and fast connections both get regular updates. The throttle could maybe be configurable though.

@Jericho

Jericho commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

a server error will silently get downloaded as the file content

Do you mean like a HTTP500 server error? If that's what you mean, the default error filter will catch it and it won't get downloaded as a file (unless the developer has deliberately removed the error filter from the pipeline, in which case I don't know exactly how it will behave. To be honest, I have never tried dispatching a HTTP request without an error filter).

@Jericho
Jericho force-pushed the GH-135_download_file branch from 43e6f7e to e7af4f7 Compare November 22, 2026 16:32
@Pathoschild

Copy link
Copy Markdown
Owner

Do you mean like a HTTP500 server error?

Yep. For example, if you do this in the integration test right now:

using IClient client = this
    .ConstructClient("https://proof.ovh.net/")
    .SetOptions(ignoreHttpErrors: true);

await client.DownloadFileAsync("files/error-404.txt", saveToPath);

Console.WriteLine(File.ReadAllText(saveToPath));

The downloaded file will having this content:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="robots" content="noindex">
  <title>404 — Not found</title>
…

The ignoreHttpErrors option is normally used when you want to handle errors yourself, but there's no way to do that with the proposed method. One option could be to replace the DownloadFileAsync method with an AsFileDownload one, so you handle errors the usual way:

IResponse response = await client.GetAsync("files/error-404.txt");
if (response.IsSuccessStatusCode)
    await response.AsFileDownload(saveToPath, progress);
else
    throw new Exception($"File API unavailable: HTTP {response.Status} {await response.AsString()}");

As an extra benefit, that would let you download any request as a file:

await client
    .PostAsync("api/download", request)
    .WithBearerAuthentication(signature)
    .AsFileDownload(saveToPath, progress);

@Jericho

Jericho commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Oh I see: you turn off error handling.

I don't think moving the extension to the IResponse interface is wise tough because we will not be able to ensure that the response is streaming which means the entire file will be buffered in memory before AsFileDownload can start writing the file to disk. Might not a problem for trivial cases but obviously not advisable when downloading large files. The whole point of streaming the response is to avoid exhausting the memory.

Maybe ignoring Http errors is simply not compatible with this new extension method and maybe we should force http errors to be handled. Like so:

        // fetch response
        IResponse response = await client
            .GetAsync(resource)
            .WithOptions(completeWhen: HttpCompletionOption.ResponseHeadersRead, ignoreHttpErrors: false)
            .WithCancellationToken(cancellationToken)
            .AsResponse()
            .ConfigureAwait(false);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add a more convenient way to download file

2 participants